const defaultAvatarUrl =
  "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0";
import Dialog from "@vant/weapp/dialog/dialog";

Page({
  data: {
    // 页面状态
    loginType: true,
    isSubmitting: false,
    uploading: false,
    show: false,
    showBindButtons: false, // 是否显示绑定选项按钮
    showBindAccount: false, // 是否显示绑定账号弹窗

    // 状态栏高度
    statusBarHeight: 0,

    // 表单数据
    loginForm: {
      phone: "",
      password: "",
      agreement: false,
    },
    registerForm: {
      nickname: "",
      phone: "",
      password: "",
      code: "",
      gender: "male",
    },
    // 绑定账号表单
    bindAccountForm: {
      phone: "",
      password: "",
    },

    // 头像相关
    headerPortraitUrl: "",

    // 微信授权登录
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: "",
    },
  },

  onLoad() {
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight,
    });

    // 获取用户信息
    wx.getUserInfo({
      success: (res) => {
        this.setData({
          "registerForm.nickname": res.userInfo.nickName,
          headerPortraitUrl: res.userInfo.avatarUrl,
        });
      },
    });
  },
  // 页面切换
  toRegister() {
    this.setData({
      loginType: !this.data.loginType,
    });
  },

  // 表单输入处理
  handlePhoneInput(e) {
    this.setData({
      "loginForm.phone": e.detail.value,
    });
  },

  handlePasswordInput(e) {
    this.setData({
      "loginForm.password": e.detail.value,
    });
  },

  handleNicknameInput(e) {
    this.setData({
      "registerForm.nickname": e.detail.value,
    });
  },

  handleRegisterPhoneInput(e) {
    this.setData({
      "registerForm.phone": e.detail.value,
    });
  },

  handleRegisterPasswordInput(e) {
    this.setData({
      "registerForm.password": e.detail.value,
    });
  },

  handleCodeInput(e) {
    this.setData({
      "registerForm.code": e.detail.value,
    });
  },

  handleAgreementChange(e) {
    console.log("协议勾选事件触发:", e.detail.value); // 勾选时输出 ["agreement"]，未勾选输出 []

    // 核心判断：value数组有值 → 勾选，无值 → 未勾选
    const isChecked = e.detail.value.length > 0;

    console.log("解析后的isChecked:", isChecked);
    this.setData({
      "loginForm.agreement": isChecked,
    });

    console.log("设置后data中的协议状态:", this.data.loginForm.agreement); // 此时应正确显示 true/false
  },

  handleGenderChange(e) {
    this.setData({
      "registerForm.gender": e.detail.value,
    });
  },

  // 头像选择与上传
  chooseAvatar() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        // 临时文件路径
        const tempFilePath = res.tempFilePaths[0];

        // 检查文件大小
        wx.getFileInfo({
          filePath: tempFilePath,
          success(fileInfo) {
            const maxSize = 5 * 1024 * 1024; // 5MB
            if (fileInfo.size > maxSize) {
              wx.showToast({
                title: "图片大小不能超过5MB",
                icon: "none",
                duration: 2000,
              });
              return;
            }

            // 显示上传中状态
            that.setData({
              uploading: true,
            });

            // 本地预览
            that.setData({
              headerPortraitUrl: tempFilePath,
            });

            // 准备上传
            const formData = {
              file: tempFilePath,
            };

            // 上传文件
            wx.uploadFile({
              url: "app/upload", // 替换为实际的上传接口
              filePath: tempFilePath,
              name: "file",
              formData: formData,
              success(uploadRes) {
                const data = JSON.parse(uploadRes.data);
                if (data.code === 200) {
                  that.setData({
                    headerPortraitUrl: data.data.url,
                  });
                  wx.showToast({
                    title: "头像上传成功",
                    icon: "success",
                    duration: 2000,
                  });
                } else {
                  wx.showToast({
                    title: data.msg || "头像上传失败",
                    icon: "none",
                    duration: 2000,
                  });
                }
              },
              fail(error) {
                console.error("头像上传异常:", error);
                wx.showToast({
                  title: "头像上传异常，请重试",
                  icon: "none",
                  duration: 2000,
                });
              },
              complete() {
                that.setData({
                  uploading: false,
                });
              },
            });
          },
        });
      },
    });
  },

  // 表单验证
  validatePhone() {
    const phone = this.data.loginForm.phone;
    if (!phone) {
      wx.showToast({
        title: "手机号不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    const reg = /^1[3-9]\d{9}$/;
    if (!reg.test(phone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    return true;
  },

  validatePassword() {
    const password = this.data.loginForm.password;
    if (!password) {
      wx.showToast({
        title: "密码不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    return true;
  },

  validateNickname() {
    const nickname = this.data.registerForm.nickname;
    if (!nickname) {
      wx.showToast({
        title: "昵称不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    return true;
  },

  validateRegisterPhone() {
    const phone = this.data.registerForm.phone;
    if (!phone) {
      wx.showToast({
        title: "手机号不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    const reg = /^1[3-9]\d{9}$/;
    if (!reg.test(phone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    return true;
  },

  validateRegisterPassword() {
    const password = this.data.registerForm.password;
    if (!password) {
      wx.showToast({
        title: "密码不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    return true;
  },

  validateCode() {
    const code = this.data.registerForm.code;
    if (!code) {
      wx.showToast({
        title: "编号不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    return true;
  },

  // 切换协议勾选状态
  toggleAgreement() {
    const newAgreementState = !this.data.loginForm.agreement;
    console.log("切换协议状态为:", newAgreementState);
    this.setData({
      "loginForm.agreement": newAgreementState,
    });
  },

  // 登录处理
  handleLogin() {
    // 全量验证
    const isPhoneValid = this.validatePhone();
    const isPwdValid = this.validatePassword();

    // 打印当前协议状态
    console.log("登录时协议状态:", this.data.loginForm.agreement);
    console.log("协议状态类型:", typeof this.data.loginForm.agreement);

    const isAgreementValid = this.data.loginForm.agreement === true;

    console.log("协议是否勾选:", isAgreementValid);

    if (!isAgreementValid) {
      wx.showToast({
        title: "请同意用户协议",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    if (!isPhoneValid || !isPwdValid) return;

    this.setData({
      isSubmitting: true,
    });

    // 登录请求
    wx.request({
      url: "https://jingqu.kuxia.top/app/User/index", // 确保URL正确
      method: "POST",
      data: {
        tel: this.data.loginForm.phone,
        pass: this.data.loginForm.password,
      },
      success: (res) => {
        console.log("登录接口返回的完整数据:", res); // 打印完整的返回数据
        if (res.statusCode === 200) {
          if (res.data.code === 1) {
            wx.showToast({
              title: res.data.msg,
              icon: "success",
              duration: 2000,
            });

            // 保存openid到本地存储（如果返回数据中有openid）
            if (res.data.data && res.data.data.openid) {
              wx.setStorageSync("openid", res.data.data.openid);
              console.log("手机号登录成功，保存openid:", res.data.data.openid);
            }

            // 跳转回首页
            setTimeout(() => {
              wx.reLaunch({
                url: "/pages/index/index",
              });
            }, 1500); // 延迟1.5秒跳转，确保用户看到成功提示
          } else {
            wx.showToast({
              title: res.data.msg || "登录失败",
              icon: "none",
              duration: 2000,
            });
          }
        } else {
          wx.showToast({
            title: "服务器错误(" + res.statusCode + ")",
            icon: "none",
            duration: 2000,
          });
        }
      },
      fail: (error) => {
        console.error("登录失败:", error);
        wx.showToast({
          title: "网络请求失败",
          icon: "none",
          duration: 2000,
        });
      },
      complete: () => {
        this.setData({
          isSubmitting: false,
        });
      },
    });
  },

  // 注册处理
  handleRegister() {
    // 全量验证
    const isNicknameValid = this.validateNickname();
    const isPhoneValid = this.validateRegisterPhone();
    const isPwdValid = this.validateRegisterPassword();
    const isCodeValid = this.validateCode();

    if (!isNicknameValid || !isPhoneValid || !isPwdValid || !isCodeValid)
      return;

    this.setData({
      isSubmitting: true,
    });

    // 准备注册数据
    const registerData = {
      ...this.data.registerForm,
      avatar: this.data.headerPortraitUrl,
    };

    // 注册请求
    wx.request({
      url: "app/User/register", // 替换为实际的注册接口
      method: "POST",
      data: registerData,
      success: (res) => {
        if (res.data.code === 1) {
          wx.showToast({
            title: res.data.msg || "注册成功",
            icon: "success",
            duration: 2000,
          });

          // 注册成功后切换到登录页
          this.toRegister();
        } else {
          wx.showToast({
            title: res.data.msg || "注册失败",
            icon: "none",
            duration: 2000,
          });
        }
      },
      fail: (error) => {
        console.error("注册失败:", error);
        wx.showToast({
          title: "注册失败",
          icon: "none",
          duration: 2000,
        });
      },
      complete: () => {
        this.setData({
          isSubmitting: false,
        });
      },
    });
  },

  // 其他功能
  handleForgotPwd() {
    wx.showToast({
      title: "忘记密码功能开发中...",
      icon: "none",
      duration: 2000,
    });
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    const { nickName } = this.data.userInfo;
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    });
  },
  onInputChange(e) {
    const nickName = e.detail.value;
    const { avatarUrl } = this.data.userInfo;
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    });
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: "展示用户信息", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
        });
      },
    });
  },

  handleScan() {
    wx.showToast({
      title: "扫码功能开发中...",
      icon: "none",
      duration: 2000,
    });
  },

  // 昵称输入处理
  onNicknameInput(e) {
    this.setData({
      "userInfo.nickName": e.detail.value,
    });
  },

  // 显示弹窗
  showPopup() {
    this.setData({ show: true });
  },

  // 关闭弹窗
  onClose() {
    this.setData({
      show: false,
      showBindButtons: false,
    });
  },

  // 点击允许按钮
  onAllowTap() {
    const { avatarUrl, nickName } = this.data.userInfo;
    // 检查头像和昵称是否填写
    if (!avatarUrl || avatarUrl === defaultAvatarUrl) {
      wx.showToast({
        title: "请上传头像",
        icon: "none",
      });
      return;
    }

    if (!nickName || nickName.trim() === "") {
      wx.showToast({
        title: "请输入昵称",
        icon: "none",
      });
      return;
    }

    // 显示绑定选项按钮
    this.setData({
      showBindButtons: true,
    });
  },

  // 已绑定账号
  onBoundAccount() {
    // 调用wx.login获取code
    wx.login({
      success: (res) => {
        console.log("wx.login success, res:", res); // 添加日志查看res内容
        if (res.code) {
          // 发起请求获取session key
          wx.request({
            url: "https://jingqu.kuxia.top/app/user/getsessionkey", // 确保这个URL是正确的
            method: "POST",
            data: {
              code: res.code,
              appid: "wx77b2d85daa5f5d00",
              secret: "2a12d3338669c184012ff2794ac9d862",
            },
            success: (response) => {
              console.log("获取session key响应", response);
              // 检查HTTP状态码
              if (response.statusCode === 200) {
                console.log("获取session key成功"); // 这条日志现在应该能打印出来了

                // 检查返回的数据结构
                if (response.data && response.data.code === 1) {
                  // 登录成功
                  wx.showToast({
                    title: "登录成功",
                    icon: "success",
                  });

                  // 保存openid到本地存储
                  if (response.data.data && response.data.data.openid) {
                    wx.setStorageSync("openid", response.data.data.openid);
                    console.log(
                      "微信登录成功，保存openid:",
                      response.data.data.openid
                    );
                  }

                  // 关闭弹窗
                  this.setData({
                    show: false,
                    showBindButtons: false,
                  });

                  // 跳转到首页
                  setTimeout(() => {
                    wx.reLaunch({
                      // 修改为reLaunch确保正确跳转
                      url: "/pages/index/index",
                    });
                  }, 1500);
                } else {
                  wx.showToast({
                    title: response.data.msg || "登录失败",
                    icon: "none",
                  });
                }
              } else if (response.statusCode === 404) {
                // 接口不存在
                wx.showToast({
                  title: "登录接口不存在",
                  icon: "none",
                });
                console.error("接口不存在，请检查URL路径是否正确");
                console.error(
                  "请求的URL:",
                  "https://jingqu.kuxia.top/app/user/getsessionkey"
                );
              } else {
                // 其他HTTP错误
                wx.showToast({
                  title: "服务器错误(" + response.statusCode + ")",
                  icon: "none",
                });
              }
            },
            fail: (error) => {
              console.error("获取session key失败", error);
              // 检查是否是域名问题
              if (
                error.errMsg &&
                error.errMsg.includes("url not in domain list")
              ) {
                wx.showToast({
                  title: "域名未授权，请联系管理员",
                  icon: "none",
                });
              } else {
                wx.showToast({
                  title: "网络请求失败",
                  icon: "none",
                });
              }
            },
          });
        } else {
          console.log("登录失败！" + res.errMsg);
          wx.showToast({
            title: "登录失败",
            icon: "none",
          });
        }
      },
      fail: (error) => {
        console.error("wx.login失败", error);
        wx.showToast({
          title: "登录失败",
          icon: "none",
        });
      },
    });
  },

  // 未绑定账号
  onUnboundAccount() {
    // 显示绑定账号弹窗
    this.setData({
      showBindAccount: true,
    });
  },
  // 关闭绑定账号弹窗
  onCloseBindAccount() {
    this.setData({
      showBindAccount: false,
    });
  },

  // 绑定手机号输入
  onBindPhoneInput(e) {
    this.setData({
      "bindAccountForm.phone": e.detail.value,
    });
  },

  // 绑定密码输入
  onBindPasswordInput(e) {
    this.setData({
      "bindAccountForm.password": e.detail.value,
    });
  },

  // 确认绑定账号
  onConfirmBindAccount() {
    const { phone, password } = this.data.bindAccountForm;

    // 检查手机号和密码是否为空（根据参数说明，这两个是可选的，但如果填写了就需要验证）
    if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none",
      });
      return;
    }

    // 添加绑定账号的逻辑
    // 调用wx.login获取code
    wx.login({
      success: (res) => {
        console.log("wx.login success, res:", res); // 添加日志查看res内容
        if (res.code) {
          // 获取全局配置中的appid
          const accountInfo = wx.getAccountInfoSync();
          const appid = accountInfo.miniProgram.appId;

          // 发起请求获取session key
          wx.request({
            url: "https://jingqu.kuxia.top/app/user/getsessionkey", // 确保这个URL是正确的
            method: "POST",
            data: {
              code: res.code,
              appid: appid,
              // 注意：secret应该从后端环境变量中获取，不应该在前端代码中传递
              // 这里移除了secret参数
            },
            success: (response) => {
              console.log("获取session key响应", response);
              // 检查HTTP状态码
              if (response.statusCode === 200) {
                // 检查是否有openid
                if (
                  response.data &&
                  response.data.data &&
                  response.data.data.openid
                ) {
                  // openid获取成功，现在调用绑定账号接口
                  console.log("获取openid成功", response.data.data.openid);
                  // 先获取openid
                  wx.request({
                    url: "https://jingqu.kuxia.top/app/user/getsessionkey", // 获取openid的接口
                    method: "POST",
                    data: {
                      code: res.code,
                      // 获取全局配置中的appid
                      appid: wx.getAccountInfoSync().miniProgram.appId,
                      // 注意：secret应该从后端环境变量中获取，不应该在前端代码中传递
                      // 这里移除了secret参数
                    },
                    success: (bindResponse) => {
                      console.log("绑定账号成功", bindResponse);
                      if (
                        bindResponse.statusCode === 200 &&
                        bindResponse.data &&
                        bindResponse.data.code === 1
                      ) {
                        wx.showToast({
                          title: "绑定成功",
                          icon: "success",
                        });

                        // 保存openid到本地存储
                        if (
                          bindResponse.data.data &&
                          bindResponse.data.data.openid
                        ) {
                          wx.setStorageSync(
                            "openid",
                            bindResponse.data.data.openid
                          );
                          console.log(
                            "微信绑定账号成功，保存openid:",
                            bindResponse.data.data.openid
                          );
                        } else if (response.data.data.openid) {
                          // 如果userInfo中没有openid，则使用之前获取的openid
                          wx.setStorageSync(
                            "openid",
                            response.data.data.openid
                          );
                          console.log(
                            "微信绑定账号成功，保存openid:",
                            response.data.data.openid
                          );
                        }

                        // 关闭绑定账号弹窗
                        this.setData({
                          showBindAccount: false,
                          show: false,
                          showBindButtons: false,
                        });

                        // 跳转到首页
                        setTimeout(() => {
                          wx.reLaunch({
                            // 修改为reLaunch确保正确跳转
                            url: "/pages/index/index",
                          });
                        }, 1500);
                      } else {
                        wx.showToast({
                          title: bindResponse.data.msg || "绑定失败",
                          icon: "none",
                        });
                      }
                    },
                    fail: (error) => {
                      console.error("绑定账号失败", error);
                      wx.showToast({
                        title: "绑定账号请求失败",
                        icon: "none",
                      });
                    },
                  });
                } else {
                  // openid获取失败
                  wx.showToast({
                    title: "获取用户标识失败",
                    icon: "none",
                  });
                  console.error("返回数据中没有openid字段", response.data);
                }
              } else {
                // HTTP状态码不是200
                wx.showToast({
                  title: "获取用户标识失败",
                  icon: "none",
                });
                console.error(
                  "获取session key失败，状态码：",
                  response.statusCode
                );
              }
            },
            fail: (error) => {
              console.error("获取session key失败", error);
              wx.showToast({
                title: "网络请求失败",
                icon: "none",
              });
            },
          });
        } else {
          console.log("登录失败！" + res.errMsg);
          wx.showToast({
            title: "登录失败",
            icon: "none",
          });
        }
      },
      fail: (error) => {
        console.error("wx.login失败", error);
        wx.showToast({
          title: "登录失败",
          icon: "none",
        });
      },
    });
  },
});
